# -*- coding: utf-8 -*-
# MobaXterm会话生成器

import os
import glob
from core.generator import SessionGenerator

class MobaXtermGenerator(SessionGenerator):
    """MobaXterm会话生成器"""
    
    def __init__(self, template_path=None):
        super().__init__(template_path)
        self.temp_files = {}
        self.roles = {}  # 用于记录所有角色和对应的索引
    
    def _init_temp_files(self, machines, output_dir):
        """初始化临时文件，动态支持任意角色"""
        # 删除已存在的会话文件
        output_file = os.path.join(output_dir, 'sessions.mxtsessions')
        if os.path.exists(output_file):
            os.remove(output_file)
        
        # 收集所有不同的角色
        unique_roles = set()
        for machine in machines:
            role = machine.get('role', '')
            if role:
                unique_roles.add(role)
        
        print(f"检测到 {len(unique_roles)} 种角色: {', '.join(unique_roles)}")
        
        # 创建主目录临时文件
        self.temp_files = {
            "main": {"path": os.path.join(output_dir, "file1.tmp"), 
                    "content": "[Bookmarks]\nSubRep=SERVERS\nImgNum=37\n"}
        }
        
        # 为每个角色创建临时文件
        for idx, role in enumerate(unique_roles, start=1):
            file_name = f"file{idx+1}.tmp"
            file_path = os.path.join(output_dir, file_name)
            self.temp_files[role] = {
                "path": file_path,
                "content": f"\n\n[Bookmarks_{idx}]\nSubRep=SERVERS\\{role.upper()}\nImgNum=41\n"
            }
            # 记录角色和索引的映射关系
            self.roles[role] = idx
        
        # 写入初始内容
        for key, item in self.temp_files.items():
            with open(item["path"], 'w', encoding='utf-8') as f:
                f.write(item["content"])
    
    def generate_session(self, machine, output_dir='.'):
        """为单台机器生成会话配置"""
        if not self.template_content:
            return False
        
        try:
            # 参数验证和防御性编程
            if not isinstance(machine, dict):
                print(f"生成会话失败: 机器信息格式错误，应为字典而不是 {type(machine)}")
                return False
            
            # 提取机器信息
            name = machine.get('hostname', '')
            ip = machine.get('IP', '')
            role = machine.get('role', '')
            
            # 必须字段检查
            if not role or not name or not ip:
                print(f"生成会话失败: 缺少必要字段 (role={role}, hostname={name}, IP={ip})")
                return False
            
            # 根据模板替换内容
            session_content = self.template_content.replace('hyperv-centos79', name).replace('192.168.100.10', ip)
            
            # 写入对应角色的临时文件
            if role in self.temp_files:
                with open(self.temp_files[role]["path"], 'a', encoding='utf-8') as f:
                    f.write(session_content)
                return True
            else:
                print(f"角色 '{role}' 无效，请确保机器列表中的角色定义一致。")
                return False
        except Exception as e:
            import traceback
            print(f"生成会话失败: {e}")
            print(f"详细错误: {traceback.format_exc()}")
            return False
    
    def generate_all_sessions(self, data_path, output_dir=None, sheet_name='Sheet1'):
        """生成所有MobaXterm会话文件"""
        if not self.template_content:
            print("错误: 模板文件未加载")
            return False
        
        # 使用统一输出路径
        moba_output_dir = self.get_output_path('mobaxterm', output_dir)
        
        # 加载数据
        machines, error = self.load_data(data_path, sheet_name)
        if error:
            print(f"加载数据文件失败: {error}")
            return False
        
        if not machines:
            print("错误: 机器列表为空")
            return False
        
        # 初始化临时文件 - 传递机器列表以检测所有角色
        self._init_temp_files(machines, moba_output_dir)
        
        # 为每台机器生成会话文件
        success_count = 0
        for machine in machines:
            if self.generate_session(machine, moba_output_dir):
                success_count += 1
        
        # 合并临时文件
        self._merge_temp_files(moba_output_dir)
        
        print(f"已成功生成 {success_count}/{len(machines)} 个MobaXterm会话文件，保存在 {moba_output_dir}")
        return success_count > 0
    
    def _merge_temp_files(self, output_dir):
        """合并临时文件为最终的MobaXterm会话文件"""
        try:
            output_file = os.path.join(output_dir, 'sessions.mxtsessions')
            temp_files = [f["path"] for f in self.temp_files.values()]
            
            with open(output_file, 'w', encoding='utf-8') as outfile:
                for temp_file in temp_files:
                    if os.path.exists(temp_file):
                        with open(temp_file, 'r', encoding='utf-8') as infile:
                            outfile.write(infile.read())
                        os.remove(temp_file)
            
            print(f"已生成MobaXterm会话文件: {output_file}")
            return True
        except Exception as e:
            print(f"合并文件失败: {e}")
            return False 